<?php
/**
 * WebHelper class file.
 *
 * @author Zhang Jinlong <466028373@qq.com>
 * @link http://www.ijianzhi.cn
 * @copyright Copyright &copy; 2013 DianJin Soft
 */

class WebHelper
{
    /**
     * 执行POST请求
     * @param string $url
     * @param array $data
     * @param array $header
     * @throws Exception
     * @return mixed
     */
    public static function post($url, $data, $header = NULL)
    {
        if (is_array($data))
        {
            $data = http_build_query($data);
        }

        $params = array(
            'http' => array(
                'method' => 'POST',
                'content' => $data,
            )
        );

        if ($header !== NULL)
        {
            $params['http']['header'] = $header;
        }

        $resource = stream_context_create($params);

        $fp = fopen($url, 'rb', FALSE, $resource);

        if (!$fp)
        {
            throw new Exception("Connect to the url \"{$url}\" fail.");
        }

        $response = stream_get_contents($fp);

        if ($response === FALSE)
        {
            throw new Exception("Get response from \"{$url}\" fail.");
        }

        return $response;
    }

    /**
     * 执行GET请求
     * @param string $url
     * @return string
     */
    public static function get($url)
    {
        $ch = curl_init($url);

        if (strpos($url, 'https://') === 0)
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

    /**
     * 获得客户端IP地址
     * @return string|NULL
     */
    public static function getIp()
    {
        $tmp = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED'
            , 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED'
            , 'HTTP_X_REAL_IP', 'REMOTE_ADDR');

        foreach ($tmp as $key)
        {
            if (isset($_SERVER[$key]))
            {
                foreach (explode(',', $_SERVER[$key]) as $ip)
                {
                    $ip = trim($ip);

                    if (filter_var($ip, FILTER_VALIDATE_IP) !== FALSE)
                    {
                        return $ip;
                    }
                }
            }
        }

        return NULL;
    }
}